package com.ibeeking.found.content.b.rest.controller.v1;

import com.ibeeking.found.content.api.feign.FileBClient;
import com.ibeeking.found.content.b.rest.service.IWxMediaFileService;
import com.ibeeking.found.content.service.common.vo.WxMediaFileVO;
import com.ibeeking.nematos.constants.enums.OperateLogTypeEnum;
import com.ibeeking.nematos.log.annotation.Log;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.result.ResponseCodeEnum;
import com.ibeeking.nematos.utils.result.ResponseResult;

import com.alibaba.fastjson.JSON;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 微信临时文件
 *
 * @Author ibeeking
 */
@RestController
@RequestMapping("/b/media/v1")
public class WxMediaFileController {

    @Resource
    private IWxMediaFileService wxMediaFileService;
    @Resource
    private FileBClient fileBClient;

    @Log(logType = OperateLogTypeEnum.SAVE, describe = "临时文件上传-目前只支持图片文件")
    @PostMapping(value = "/upload")
    @ResponseBody
    public WxMediaFileVO uploadMedia(@RequestPart("file") MultipartFile multipartFile) throws IOException, WxErrorException {
        String originalFilename = multipartFile.getOriginalFilename();
        String fileType = StringUtils.EMPTY;
        if (StringUtils.isNotBlank(originalFilename) && originalFilename.contains(".")) {
            String[] split = originalFilename.split("\\.");
            fileType = split[1];
        }
        WxMediaFileVO result = new WxMediaFileVO();

        ResponseResult<String> uploadResult = fileBClient.uploadFile(multipartFile);
        LogUtils.info("文件上传返回值 uploadResult:" + JSON.toJSONString(uploadResult));
        if (ResponseCodeEnum.SUCCESS.getCode().equals(uploadResult.getCode())) {
            String url = uploadResult.getData();
            result.setUrl(url);
        }
        String mediaId = wxMediaFileService.uploadMedia(multipartFile.getInputStream(), fileType);
        result.setMediaId(mediaId);

        return result;
    }
}
